<template>
  <div>
    <h2>About Page</h2>
    <p>This is the About Page.</p>
    <span>当前用户的id：{{ id }}</span>
  </div>
  <div>
    <button @click="fetchData()">点击批量请求接口</button><br>
    <span>接口1：{{ data1 }}</span><br>
    <span>接口2：{{ data2 }}</span><br>
    <span>接口3：{{ data3 }}</span><br>
  </div>
  <div>
    <button @click="fetchData2()">点击批量请求接口</button><br>

  </div>
</template>
  
<script>
import axios from 'axios';
export default {
  name: 'AboutPage',
  data() {
    return {
      id: null,
      data1: '无敌',
      data2: '天下',
      data3: '真棒',
    }
  },
  methods: {
    async fetchData() {
      try {
        let response1 = axios.get('/test');
        let response2 = axios.get('/test2');
        let response3 = axios.get('/test3');
        let [result1, result2, result3] = await axios.all([response1, response2, response3]);
        this.data1 = result1.data.answer;
        this.data2 = result2.data;
        this.data3 = result3.data;
      } catch (error) {
        alert('An error occurred:', error);
      }
    },
    //第二种写法
    fetchData2() {
      let response1 = axios.get('/test');
      let response2 = axios.get('/test2');
      let response3 = axios.get('/test3');
      axios.all([response1, response2, response3])
      //使用箭头函数可以确保回调函数中的 this 指向当前的组件实例，从而正常访问 data1、data2 和 data3。
      //这是因为箭头函数不会改变它们的 this 上下文，而是继承自外部作用域的 this。
        .then(axios.spread((res1, res2, res3) => {
          //三个请求都完成了
          this.data1 = res1.data.answer;
          this.data2 = res2.data.answer;
          this.data3 = res3.data.answer;
        })).catch(error => {
          alert("An error occurred", error);
        });
    }
  },
  created() {
    this.id = this.$route.params.id;
  }
};
</script>